package tongcheng.com.tongcheng.ui.yemian.shenfen.activity;

import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.bigkoo.pickerview.OptionsPickerView;
import com.bumptech.glide.Glide;
import com.google.gson.Gson;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.entity.LocalMedia;
import com.yanzhenjie.nohttp.FileBinary;
import com.yanzhenjie.nohttp.RequestMethod;

import org.json.JSONArray;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import tongcheng.com.tongcheng.ConStans;
import tongcheng.com.tongcheng.R;
import tongcheng.com.tongcheng.base.BaseActivity;
import tongcheng.com.tongcheng.bean.MyCityBean;
import tongcheng.com.tongcheng.bean.StatusBean;
import tongcheng.com.tongcheng.bean.UpImageBean;
import tongcheng.com.tongcheng.network.CallServer;
import tongcheng.com.tongcheng.network.MyRequest;
import tongcheng.com.tongcheng.network.OnCallBack;
import tongcheng.com.tongcheng.utils.GetJsonDataUtil;
import tongcheng.com.tongcheng.utils.GsonUtil;
import tongcheng.com.tongcheng.utils.Setting;
import tongcheng.com.tongcheng.utils.ShowToast;
import tongcheng.com.tongcheng.widght.PhotoPopWindow;

public class WanShanZiliao_Qiye_qiyeActivity extends BaseActivity {
    int x = -1, y = -1, z = -1;
    String tx;
    @Bind(R.id.back)
    ImageView mBack;
    @Bind(R.id.back_text)
    TextView mBackText;
    @Bind(R.id.title)
    TextView mTitle;
    @Bind(R.id.title_bar)
    RelativeLayout mBg;
    @Bind(R.id.install_name)
    EditText mInstallName;
    @Bind(R.id.install_area)
    TextView mInstallArea;
    @Bind(R.id.wanshan_addaddress)
    LinearLayout mWanshanAddaddress;
    @Bind(R.id.install_xiangxiarea)
    EditText mInstallXiangxiarea;
    @Bind(R.id.textView)
    TextView mTextView;
    @Bind(R.id.install_phone)
    EditText mInstallPhone;
    @Bind(R.id.wanshan_qiye_lllast)
    LinearLayout mWanshanQiyeLllast;
    @Bind(R.id.install_beizhu)
    EditText mInstallBeizhu;
    @Bind(R.id.install_ll1)
    LinearLayout mInstallLl1;
    @Bind(R.id.install_next)
    Button mInstallNext;
    @Bind(R.id.install_button1)
    ImageButton mInstallButton1;
    @Bind(R.id.install_button2)
    ImageButton mInstallButton2;
    @Bind(R.id.install_button3)
    ImageButton mInstallButton3;
    @Bind(R.id.tv_shanChu1)
    TextView tv_shanChu1;
    @Bind(R.id.tv_shanChu2)
    TextView tv_shanChu2;
    @Bind(R.id.tv_shanChu3)
    TextView tv_shanChu3;

    private List<LocalMedia> selectList;

    @Override
    public Integer initResid() {
        return R.layout.activity_wan_shan_ziliao__qiye_qiye;
    }

    @Override
    public void initCreate(Bundle savedInstanceState) {

        if (thread == null) {//如果已创建就不再重新创建子线程了
            thread = new Thread(new Runnable() {
                @Override
                public void run() {
                    // 写子线程中的操作,解析省市区数据
                    initJsonData();
                }
            });
            thread.start();
        }

        settitlebar(mBg);
        mTitle.setText("完善资料");
        mBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });
        mWanshanAddaddress.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (isLoaded) {
                    ShowPickerView();
                } else {
                    mHandler.sendEmptyMessage(MSG_LOAD_DATA);
                    Toast.makeText(WanShanZiliao_Qiye_qiyeActivity.this, "数据暂未解析成功，请等待", Toast.LENGTH_SHORT).show();
                }
            }
        });


        tv_shanChu1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                imagename1 = "";
                Glide.with(WanShanZiliao_Qiye_qiyeActivity.this).load(imagename1).into(mInstallButton1);
            }
        });

        tv_shanChu2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                imagename2 = "";
                Glide.with(WanShanZiliao_Qiye_qiyeActivity.this).load(imagename2).into(mInstallButton2);
            }
        });

        tv_shanChu3.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                imagename3 = "";
                Glide.with(WanShanZiliao_Qiye_qiyeActivity.this).load(imagename3).into(mInstallButton3);
            }
        });

        mInstallButton1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (TextUtils.isEmpty(imagename1)) {
                    temp = 1;
                    PhotoPopWindow photoPopWindow = new PhotoPopWindow(WanShanZiliao_Qiye_qiyeActivity.this, WanShanZiliao_Qiye_qiyeActivity.this);
                    photoPopWindow.show(mBg);
                }

            }
        });


        mInstallButton2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (TextUtils.isEmpty(imagename2)) {
                    temp = 2;
                    PhotoPopWindow photoPopWindow = new PhotoPopWindow(WanShanZiliao_Qiye_qiyeActivity.this, WanShanZiliao_Qiye_qiyeActivity.this);
                    photoPopWindow.show(mBg);
                }

            }
        });


        mInstallButton3.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                if (TextUtils.isEmpty(imagename3)) {
                    temp = 3;
                    PhotoPopWindow photoPopWindow = new PhotoPopWindow(WanShanZiliao_Qiye_qiyeActivity.this, WanShanZiliao_Qiye_qiyeActivity.this);
                    photoPopWindow.show(mBg);
                }

            }
        });


        //提交
        mInstallNext.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String name = mInstallName.getText().toString().trim();
                String area = mInstallArea.getText().toString().trim();
                String allarea = mInstallXiangxiarea.getText().toString().trim();
                String phone = mInstallPhone.getText().toString().trim();
                String beizhu = mInstallBeizhu.getText().toString().trim();
                if (TextUtils.isEmpty(name)) {
                    ShowToast.showToast("公司名称不能为空");
                } else if (TextUtils.isEmpty(area)) {
                    ShowToast.showToast("地区不能为空");
                } else if (TextUtils.isEmpty(allarea)) {
                    ShowToast.showToast("详细地址不能为空");
                } else if (TextUtils.isEmpty(phone)) {
                    ShowToast.showToast("电话不能为空");
                } else if (TextUtils.isEmpty(beizhu)) {
                    ShowToast.showToast("备注不能为空");
                } else if (TextUtils.isEmpty(imagename1)&&TextUtils.isEmpty(imagename2)&&TextUtils.isEmpty(imagename3)) {
                    ShowToast.showToast("请上传一张营业执照照片");
                }else {
                    UpInfo();
                }
                /*startactivity(WanShanZiliao_Qiye_qiyeActivity.this, InstallUpLoadPic.class);*/
            }
        });


    }

    private void ShowPickerView() {// 弹出选择器

        OptionsPickerView pvOptions = new OptionsPickerView.Builder(this, new OptionsPickerView.OnOptionsSelectListener() {
            @Override
            public void onOptionsSelect(int options1, int options2, int options3, View v) {
                //返回的分别是三个级别的选中位置
                x = options1;
                y = options2;
                z = options3;

                if (options1Items.get(options1).getV().equals(options2Items.get(options1).get(options2)

                )) {
                    tx =
                            options2Items.get(options1).get(options2) +
                                    options3Items.get(options1).get(options2).get(options3);

                } else {
                    tx = options1Items.get(options1).getV() +
                            options2Items.get(options1).get(options2) +
                            options3Items.get(options1).get(options2).get(options3);

                }

                //tv_address.setText("所在地址 :"+tx);
                mInstallArea.setText(tx);

            }
        })

                .setTitleText("城市选择")
                .setDividerColor(Color.BLACK)
                .setTextColorCenter(Color.BLACK) //设置选中项文字颜色
                .setContentTextSize(20)
                .setOutSideCancelable(false)// default is true
                .build();

        /*pvOptions.setPicker(options1Items);//一级选择器
        pvOptions.setPicker(options1Items, options2Items);//二级选择器*/
        pvOptions.setPicker(datas, options2Items, options3Items);//三级选择器
        pvOptions.show();
    }

    private boolean isLoaded = false;

    private ArrayList<ArrayList<String>> options2Items = new ArrayList<>();
    private ArrayList<ArrayList<ArrayList<String>>> options3Items = new ArrayList<>();
    private Thread thread;
    private static final int MSG_LOAD_DATA = 0x0001;
    private static final int MSG_LOAD_SUCCESS = 0x0002;
    private static final int MSG_LOAD_FAILED = 0x0003;
    int temp = 0;
    String imagename1 = "";
    String imagename2 = "";
    String imagename3 = "";

    private ArrayList<MyCityBean> options1Items = new ArrayList<>();
    private Handler mHandler = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case MSG_LOAD_DATA:
                    if (thread == null) {//如果已创建就不再重新创建子线程了
                        thread = new Thread(new Runnable() {
                            @Override
                            public void run() {
                                // 写子线程中的操作,解析省市区数据
                                initJsonData();
                            }
                        });
                        thread.start();
                    }
                    break;

                case MSG_LOAD_SUCCESS:

                    isLoaded = true;
                    break;

                case MSG_LOAD_FAILED:
                    Toast.makeText(WanShanZiliao_Qiye_qiyeActivity.this, "省市区数据损坏，请重新下载应用", Toast.LENGTH_SHORT).show();
                    break;

            }
        }
    };
    ArrayList<String> datas;
    String JsonData;
    ArrayList<MyCityBean> jsonBean;

    private void initJsonData() {//解析数据

        /**
         * 注意：assets 目录下的Json文件仅供参考，实际使用可自行替换文件
         * 关键逻辑在于循环体
         *
         * */
        JsonData = new GetJsonDataUtil().getJson(this, "city.json");//获取assets目录下的json文件数据
        Log.e("jsonsld", JsonData);
        jsonBean = parseData(JsonData);//用Gson 转成实体

        /**
         * 添加省份数据
         *
         * 注意：如果是添加的JavaBean实体，则实体类需要实现 IPickerViewData 接口，
         * PickerView会通过getPickerViewText方法获取字符串显示出来。
         */
        datas = new ArrayList<>();
        options1Items = jsonBean;
        for (int i = 0; i < jsonBean.size(); i++) {
            datas.add(jsonBean.get(i).getV());

        }

        for (int i = 0; i < jsonBean.size(); i++) {//遍历省份
            ArrayList<String> CityList = new ArrayList<>();//该省的城市列表（第二级）
            ArrayList<ArrayList<String>> Province_AreaList = new ArrayList<>();//该省的所有地区列表（第三极）

            for (int c = 0; c < jsonBean.get(i).getN().size(); c++) {//遍历该省份的所有城市
                String CityName = jsonBean.get(i).getN().get(c).getV().toString();
                CityList.add(CityName);//添加城市

                ArrayList<String> City_AreaList = new ArrayList<>();//该城市的所有地区列表

                //如果无地区数据，建议添加空字符串，防止数据为null 导致三个选项长度不匹配造成崩溃
                if (jsonBean.get(i).getN().get(c).getN() == null
                        || jsonBean.get(i).getN().get(c).getN().size() == 0) {
                    City_AreaList.add("");
                } else {

                    for (int d = 0; d < jsonBean.get(i).getN().get(c).getN().size(); d++) {//该城市对应地区所有数据
                        String AreaName = jsonBean.get(i).getN().get(c).getN().get(d).getV().toString();

                        City_AreaList.add(AreaName.toString());//添加该城市所有地区数据
                    }
                }
                Province_AreaList.add(City_AreaList);//添加该省所有地区数据
            }

            /**
             * 添加城市数据
             */
            options2Items.add(CityList);

            /**
             * 添加地区数据
             */
            options3Items.add(Province_AreaList);
        }

        mHandler.sendEmptyMessage(MSG_LOAD_SUCCESS);

    }


    public ArrayList<MyCityBean> parseData(String result) {//Gson 解析
        ArrayList<MyCityBean> detail = new ArrayList<>();
        try {
            JSONArray data = new JSONArray(result);
            Gson gson = new Gson();
            for (int i = 0; i < data.length(); i++) {
                MyCityBean entity = gson.fromJson(data.optJSONObject(i).toString(), MyCityBean.class);
                detail.add(entity);
            }
        } catch (Exception e) {
            e.printStackTrace();
            mHandler.sendEmptyMessage(MSG_LOAD_FAILED);
        }
        return detail;
    }/**/


    private void UpInfo() {
        StringBuffer sb = new StringBuffer();
        sb.append(imagename1 + ",");
        sb.append(imagename2 + ",");
        sb.append(imagename3 + ",");
        Log.e("login", sb.toString());
        MyRequest request = new MyRequest(ConStans.UpChangInfo_Url, RequestMethod.POST);
        request.add("type", Setting.getShenfen());
        request.add("phone", Setting.getPhone());
        request.add("user_name", mInstallName.getText().toString().trim());
        request.add("address", mInstallArea.getText().toString().trim());
        request.add("address_detail", mInstallXiangxiarea.getText().toString().trim());
        request.add("tel", mInstallPhone.getText().toString().trim());
        request.add("documents_features", sb.toString());//营业执照
        request.add("remark", mInstallBeizhu.getText().toString().trim());
        CallServer.getInstance().addPost(this,request, 1, new OnCallBack() {
            @Override
            public void OnSuccess(int what, String json, Object ject) {
                Log.e("上传资料",json);
                StatusBean statusBean = GsonUtil.GsonToBean(json, StatusBean.class);
                if (statusBean != null) {
                    if (statusBean.msg != null) {
                        ShowToast.showToast(statusBean.msg);
                    }

                    if (statusBean.status == 1) {
                       // startactivity(WanShanZiliao_Qiye_qiyeActivity.this, YinHangCardActivity.class);
                        startactivity(WanShanZiliao_Qiye_qiyeActivity.this, BaoZhenJinActivity.class);
                    }
                }
            }
        });
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case PictureConfig.CHOOSE_REQUEST:
                    // 图片选择结果回调
                    selectList = PictureSelector.obtainMultipleResult(data);
                    // 例如 LocalMedia 里面返回三种path
                    // 1.media.getPath(); 为原图path
                    // 2.media.getCutPath();为裁剪后path，需判断media.isCut();是否为true
                    // 3.media.getCompressPath();为压缩后path，需判断media.isCompressed();是否为true
                    // 如果裁剪并压缩了，以取压缩路径为准，因为是先裁剪后压缩的
                    // ShowToast.showToast("我被回调了");
                    UpImage(selectList);
                    break;
            }
        }
    }
    //上传图片
    private void UpImage(List<LocalMedia> selectList) {
        MyRequest request = new MyRequest(ConStans.UpImage_Url, RequestMethod.POST);
        request.add("code", "image");
        request.add("num", selectList.size());
        Log.e("size", selectList.size()+"");
        for (int i = 0; i < selectList.size(); i++) {
            Log.e("size", "image" + (i + 1));
            request.add("image" + (i+1), new FileBinary(new File(selectList.get(i).getPath())));
        }

        CallServer.getInstance().addPost(this,request, 1, new OnCallBack() {
            @Override
            public void OnSuccess(int what, String json, Object ject) {
                UpImageBean upImageBean = GsonUtil.GsonToBean(json, UpImageBean.class);
                if (upImageBean != null) {
                    switch (temp) {
                        case 1:
                            mInstallButton1.setScaleType(ImageView.ScaleType.FIT_XY);
                            imagename1 = upImageBean.data.get(0).filename;
                            Glide.with(WanShanZiliao_Qiye_qiyeActivity.this).load(ConStans.BaseUrl_Test_url+upImageBean.data.get(0).filename).into(mInstallButton1);
                            break;
                        case 2:
                            mInstallButton2.setScaleType(ImageView.ScaleType.FIT_XY);
                            imagename2 = upImageBean.data.get(0).filename;
                            Glide.with(WanShanZiliao_Qiye_qiyeActivity.this).load(ConStans.BaseUrl_Test_url+upImageBean.data.get(0).filename).into(mInstallButton2);
                            break;
                        case 3:
                            mInstallButton3.setScaleType(ImageView.ScaleType.FIT_XY);
                            imagename3 = upImageBean.data.get(0).filename;
                            Glide.with(WanShanZiliao_Qiye_qiyeActivity.this).load(ConStans.BaseUrl_Test_url+upImageBean.data.get(0).filename).into(mInstallButton3);
                            break;
                    }
                }
            }
        });

    }


}
